package com.ht.modules.authentication.controller;

import com.gexin.fastjson.JSON;
import com.ht.entity.Result;
import com.ht.modules.ai.app.entity.AppInfo;
import com.ht.modules.ai.app.service.IAppInfoService;
import com.ht.modules.ai.company.entity.Company;
import com.ht.modules.ai.company.service.ICompanyService;
import com.ht.modules.authentication.utils.AesUtil;
import com.ht.modules.authentication.utils.JwtUtil;
import com.ht.modules.authentication.utils.Md5Util;
import com.ht.modules.authentication.utils.RsaUtil;
import com.ht.modules.authentication.vo.TokenVo;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证
 */
@RestController
public class AuthController implements VersionController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IAppInfoService appInfoService;

    /**
     * 获取认证信息
     **/
    @PostMapping("/getToken")
    public Result<?> getToken(@RequestBody TokenVo tokenVo) {
        try {
            Integer companyId = tokenVo.getCompanyId();
            if (null == companyId) {
                return Result.error("企业信息不能为空");
            }
            Integer appId = tokenVo.getAppId();
            if (null == appId) {
                return Result.error("应用不能为空");
            }
            Company dbCompany = companyService.getById(companyId);
            if (null == dbCompany) {
                return Result.error("企业信息不存在");
            }
            AppInfo dbAppInfo = appInfoService.queryById(appId);
            if (null == dbAppInfo) {
                return Result.error("企业应用不存在");
            }
            tokenVo.setCompanyCode(dbCompany.getCode());
            tokenVo.setAppSecret(dbAppInfo.getAccessKey());
            String sign = tokenVo.getSign();
            // 将企业编码和ID拼接成一个字符串，使用应用对称加密算法进行加密
            String companyCodeAndId = dbCompany.getCode() + "_" + dbCompany.getId();
            String encrypt = AesUtil.encrypt(companyCodeAndId, dbAppInfo.getAccessKey());
            // 使用MD5算法对加密后的字符串进行加密
            sign = Md5Util.MD5Encode(encrypt, "UTF-8");
            // 再通过非对称公钥对MD5加密后的字符串进行加密
            sign = RsaUtil.decryptByPrivateKey(sign, dbCompany.getPublicKey(), RsaUtil.Mode.PUBLIC_ENCRYPT);
            System.out.println("sign = " + sign);
            tokenVo.setSign(null);
            tokenVo.setToken(null);
            tokenVo.setTimestamp(null);
            String infoJson = JSON.toJSONString(tokenVo);
            String tokenStr = jwtUtil.generateToken(sign, infoJson, dbAppInfo.getAccessKey(), 24 * 60 * 60 * 1000);
            return Result.ok("操作成功", tokenStr);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }

    }

    /**
     * 验证认证信息
     **/
    @PostMapping("/verifyToken")
    public Result<?> verifyToken(@RequestBody TokenVo tokenVo) {
        String token = tokenVo.getToken();
        if (Strings.isBlank(token)) {
            return Result.error("token不能为空");
        }
        Integer companyId = tokenVo.getCompanyId();
        if (null == companyId) {
            return Result.error("企业信息不能为空");
        }
        Integer appId = tokenVo.getAppId();
        if (null == appId) {
            return Result.error("应用不能为空");
        }
        Company dbCompany = companyService.getById(companyId);
        if (null == dbCompany) {
            return Result.error("企业信息不存在");
        }
        AppInfo dbAppInfo = appInfoService.queryById(appId);
        if (null == dbAppInfo) {
            return Result.error("企业应用不存在");
        }
        tokenVo.setCompanyCode(dbCompany.getCode());
        tokenVo.setAppSecret(null);
        tokenVo.setSign(null);
        tokenVo.setToken(null);
        tokenVo.setTimestamp(null);
        String infoJson = JSON.toJSONString(tokenVo);
        boolean result = jwtUtil.verify(token, dbCompany.getCode() + "_" + dbCompany.getId(), infoJson, dbAppInfo.getAccessKey());
        return Result.ok("操作成功", result);
    }
}
